package chapter05;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 两阶段终止案例
 */
@Slf4j
public class TwoPhaseEndTest {
    public static void main(String[] args) throws InterruptedException {
        SystemMonitor systemMonitor = new SystemMonitor();
        systemMonitor.start();
        TimeUnit.MILLISECONDS.sleep(3500);
        systemMonitor.stop();
    }

    static class SystemMonitor{
        private Thread monitor;
        private volatile boolean flag=true;
        public void start(){
            monitor=new Thread(()->{
                while (flag){
                    Thread currentThread = Thread.currentThread();
                    try {
                        Thread.sleep(1000);
                        log.info("正在执行监控程序执行");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        continue;
                    }
                }
                // 线程被打断
                log.info("线程被打断，处理后事");
            },"monitor");
            monitor.start();
        }
        public void stop(){
            flag=false;
            monitor.interrupt();
        }
    }
}
